package db

import (
	"alarm_service/internal/config"
	"fmt"
	"github.com/google/wire"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var ProviderSet = wire.NewSet(New)

type DB struct {
	DB *gorm.DB
}

func New(config *config.Config) *DB {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.DB.User,
		config.DB.Password,
		config.DB.Host,
		config.DB.Port,
		config.DB.Name,
	)
	fmt.Println("[InitMysqlDatabase] connection database with dsn:" + dsn)
	// 自定义 Logger
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             100 * time.Millisecond, // 慢 SQL 阈值
			LogLevel:                  logger.Info,            // Log level
			IgnoreRecordNotFoundError: true,                   // 忽略 ErrRecordNotFound 错误
			Colorful:                  true,                   // 禁用彩色打印（在 Windows 上可能不起作用）
		},
	)

	mysqlDB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	d, _ := mysqlDB.DB()
	d.SetConnMaxLifetime(60 * time.Second)
	d.SetMaxIdleConns(4)
	d.SetConnMaxIdleTime(30 * time.Second)
	mysqlDB = mysqlDB.Debug()

	return &DB{mysqlDB}

}
